package com.youth.controller.jsr303;

import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;

import com.youth.entity.UserInfo;

/**
 * JSR 303 – Bean Validation 是一个数据验证的规范.
 * hibernate-validate实现了此规范，此处使用hibernate-validate框架进行校验
 * @author xiangke
 *
 */
@Controller
@RequestMapping("")
public class HibernateValidatorController {
	
	/**
	 * save时id可以为空
	 * update时id不能为空
	 */
	@RequestMapping("saveUserInfo")
	public String saveUserInfo(@Validated(Insert.class) UserInfo userinfo, Errors errors, Model model){
		extractError(errors, model);
		return "";
	}
	
	@RequestMapping("updUserInfo")
	public String updUserInfo(@Validated(Update.class) UserInfo userinfo, Errors errors, Model model){
		extractError(errors, model);
		return "";
	}



	private void extractError(Errors errors, Model model) {
		List<FieldError> fel = errors.getFieldErrors();
		for (FieldError fe : fel) {
			String field = fe.getField(); // 字段
			// fe.getObjectName() 字段所在对象
			String defaultMsg = fe.getDefaultMessage();  // 错误提示信息
			model.addAttribute("error_" + field, defaultMsg);
		}
	}
	
}
